﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace GitDiff
{
    class History
    {
        #region HistoryEntity
        public class HistoryEntity
        {
            private string _fileName = string.Empty;
            private string _saveDate = string.Empty;
            private string _subFile = string.Empty;
            private string _newDirectionPath = string.Empty;
            private string _oldDirectionPath = string.Empty;

            public string FileName
            {
                get
                {
                    return _fileName;
                }

                set
                {
                    _fileName = value;
                }
            }

            public string SaveDate
            {
                get
                {
                    return _saveDate;
                }

                set
                {
                    _saveDate = value;
                }
            }

            public string SubFile
            {
                get
                {
                    return _subFile;
                }

                set
                {
                    _subFile = value;
                }
            }

            public string NewDirectionPath
            {
                get
                {
                    return _newDirectionPath;
                }

                set
                {
                    _newDirectionPath = value;
                }
            }

            public string OldDirectionPath
            {
                get
                {
                    return _oldDirectionPath;
                }

                set
                {
                    _oldDirectionPath = value;
                }
            }
        }
        #endregion

        public static readonly History Instance = new History();
        private string filePath;
        private List<HistoryEntity> userProfies = new List<HistoryEntity>();
        public bool HistroyXML()
        {
            bool bResult = false;
            //filePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "GitDiffHistory.xml");
            try
            {
                filePath = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "GitDiffHistory.xml");

                if (!File.Exists(filePath))
                    File.Create(filePath);

                bResult = true;
            }
            catch(Exception ex)
            {
                
            }
            return bResult;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string ReadSetting(string key)
        {
            var up = userProfies.FirstOrDefault(m => m.FileName == key);
            if (up != null)
                return userProfies.FirstOrDefault(m => m.OldDirectionPath == key).FileName;
            else
                return string.Empty;
        }


        /// <summary>
        /// 写入历史记录
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void WriteSetting(HistoryEntity item)
        {
            var us = userProfies.FirstOrDefault(m => m.FileName == item.FileName);
            if (us != null)
                userProfies.Remove(us);
            userProfies.Add(new HistoryEntity
            {
                FileName = item.FileName,
                SaveDate = item.SaveDate,
                NewDirectionPath = item.NewDirectionPath,
                OldDirectionPath = item.OldDirectionPath,
                SubFile = item.SubFile
            });
            SaveHistroyXML();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        public void RemoveSetting(string key)
        {
            var us = userProfies.FirstOrDefault(m => m.FileName == key);
            if (us != null)
            {
                userProfies.Remove(us);
                SaveHistroyXML();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void SaveHistroyXML()
        {
            try
            {
                #region [XML序列化方式]
                //<?xml version="1.0"?>
                //<ArrayOfUserProfie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                //  <UserProfie>
                //    <Key>key1</Key>
                //    <Value>1</Value>
                //  </UserProfie>
                //  <UserProfie>
                //    <Key>key2</Key>
                //    <Value>2</Value>
                //  </UserProfie>
                //</ArrayOfUserProfie>
                //XmlSerializer serializer = new XmlSerializer(typeof(List<HistoryEntity>));
                //using (FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate))
                //{
                //    serializer.Serialize(stream, userProfies);
                //}
                #endregion

                #region [Linq to XML方式]
                //var domLinq = new XElement("AppSettings",
                //                            from c in userProfies
                //                            select new XElement("add",
                //                            new XAttribute("FileName", c.FileName),
                //                            new XAttribute("NewDirectionPath", c.NewDirectionPath),
                //                            new XAttribute("OldDirectionPath", c.OldDirectionPath),
                //                            new XAttribute("SaveDate", c.SaveDate)
                //                            ));
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(filePath);
                var doc = new XDocument(
                            from c in userProfies
                            select new XElement("History",
                                new XElement("FileName", c.FileName),
                                new XElement("SaveDate", c.SaveDate),
                                new XElement("NewDirectionPath", c.NewDirectionPath),
                                new XElement("OldDirectionPath", c.OldDirectionPath),
                                new XElement("SubFile", c.SubFile)
                                )
                            );
                //xmlDoc.AppendChild();
                #endregion
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 载入XML文件
        /// </summary>
        private void LoadHistoryXML()
        {
            if (File.Exists(filePath))
            {
                try
                {
                    XmlSerializer xs = new XmlSerializer(typeof(List<HistoryEntity>));
                    using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        userProfies = (List<HistoryEntity>)xs.Deserialize(fs);
                    }
                    #region [Linq to XML方式]                   
                    //XDocument xdoc = XDocument.Load(filePath);<br>                    
                    //var userConfiLst = from a in xdoc.Descendants("AppSettings").Elements("add")<br>                    
                    //                   select new UserConfig<br>                    
                    //                   {<br>                    
                    //                       Key = a.Attribute("key").Value,<br>                    
                    //                       Value = a.Attribute("value").Value,<br>                    
                    //                   };<br>                    
                    //this.userProfies = userConfiLst.ToList(); <br>                    
                    #endregion
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }
}
